package com.freesky.provider.image.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class UploadUtil {
    private  static Logger logger = LoggerFactory.getLogger(UploadUtil.class);
    /**
     * 重命名图片
     *
     * @param fileName
     * @return
     */
    public static String renamePic(String fileName) {
        String extName = fileName.substring(fileName.lastIndexOf("."));
        return UUID.randomUUID().toString().replace("-", "") + extName;
    }

    /**
     * @param inputStream
     * @param imageBaseUrl  读取图片服务器地址
     * @param fileName 图片名
     * @param savePath 本地保存文件地址
     * @return
     */
    //图片上传
    public static String save( InputStream inputStream, String imageBaseUrl, String savePath, String fileName) {
        OutputStream output = null;
        String fileUrl = "";
        try {
            //重命名图片
            String targertFileName = renamePic(fileName);
            fileUrl =imageBaseUrl+ targertFileName;
            logger.info("图片访问路径："+fileUrl);
            //检测文件夹是否存在，不存在就创建
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }

            File file = new File(savePath, targertFileName);
            output = new FileOutputStream(file);
            // 每块数据的保存大小
            byte[] data = new byte[2048];
            // 保存每次的个数
            int temp = 0;
            while ((temp = inputStream.read(data)) != -1) {
                output.write(data, 0, temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("图片上传失败",e);
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return fileUrl;
    }

}

